package vip.zhenzicheng.algorithm.demo.sum;

/**
 * 求N阶乘合
 *
 * @author zhenzicheng
 * @date: 2022-05-16 19:34
 */
public class SumOfFactorial {

  public static void main(String[] args) {
    // 普通方式
    System.out.println(f1(1024));
    // 最优方式
    System.out.println(f2(1024));
  }

  public static long f1(int N) {
    long ans = 0;
    for (int i = 1; i <= N; i++) {
      ans += factorial(i);
    }
    return ans;
  }

  private static long factorial(int N) {
    long ans = 1;
    for (int i = 1; i <= N; i++) {
      ans *= i;
    }
    return ans;
  }

  /**
   * 优化过后，!N = !(n-1)*N
   */
  public static long f2(int N) {
    long ans = 0;
    long cur = 1;
    for (int i = 1; i <= N; i++) {
      cur = cur * i;
      ans += cur;
    }
    return ans;
  }

}
